#include <stdio.h>
#include <stdlib.h>
#include <sys/utsname.h>

#include "membuf.h"
#include "kernel_org_memread.h"
#include "site_parse.h"

static void
report_version_info(int extern_version)
{
	int current_version;
	struct utsname linux_version_info;
	if (uname(&linux_version_info) == -1)
		return;
	current_version = str_to_ver_id(linux_version_info.release);
	printf("current kernel version id: 0x%08x\n"
		"latest kernel version id: 0x%08x\n"
		"%s\n",
		current_version, extern_version,
		current_version < extern_version ? "can update" : "no updates");
}

static void
init_membuf(struct membuf *inp)
{
	inp->data_len = 0UL;
	inp->offset = 0UL;
	inp->start_ptr = malloc(INPUT_WEB_BUF_SIZE);
	inp->total_bytes = INPUT_WEB_BUF_SIZE;
}

static void
release_membuf(struct membuf *target)
{
	if (target->start_ptr)
		free(target->start_ptr);
	target->start_ptr = NULL;
	target->total_bytes = 0UL;
	target->offset = 0UL;
	target->data_len = 0UL;
}

int
main(void)
{
	int exit_code = 0;
	struct membuf input;
	init_membuf(&input);
	if (read_kernel_org_site(&input) > 0UL) {
		char ref[256];
		((char *)input.start_ptr)[input.data_len] = '\0';
		const char *id_text = find_latest_id_ref(input.start_ptr);
#ifdef _DEBUG
		fwrite(input.start_ptr, 1UL, input.data_len, stdout);
		printf("\n***\nSTATS\ntotal_bytes = %lu\ndata_len = %lu\n",
				input.total_bytes, input.data_len);
#endif
		if (id_text != NULL &&
		(copy_latest_ref(id_text, ref, sizeof(ref)) == 0)) {
			printf("source archive ref: %s\n", ref);
			report_version_info(vers_latest(id_text));
		}
	} else {
		exit_code = 1;
	}
	release_membuf(&input);
	return exit_code;
}

